package com.hr.dao.impl;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.hr.dao.NoticeDao;
import com.hr.pojo.Notice;
import com.hr.utils.C3P0Utils;

public class NoticeDaoImpl implements NoticeDao {
	private QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
	@Override
	public List findAllNotices() {
		String sql ="select * from hr_notice";
		List<Notice> list = null;
		try {
			 list = queryRunner.query(sql, new BeanListHandler<Notice>(Notice.class));
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}
	@Override
	public void saveNotice(Notice notice) {
		SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		notice.setTime(Timestamp.valueOf(simpleDate.format(notice.getTime())));
		String sql ="insert into hr_notice(title,content,time) values(?,?,?)";
		Object[] params = new Object[]{notice.getTitle(),notice.getContent(),notice.getTime()};
		try {
			queryRunner.update(sql, params);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	@Override
	public Notice findNoticeById(String id) {
		String sql ="select * from hr_notice where id = ? ";
		Notice notice = null;
		try {
			notice = queryRunner.query(sql, new BeanHandler<>(Notice.class), id);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return notice;
	}
	@Override
	public void updateNotice(Notice notice) {
		String sql ="update hr_notice set title = ?,content= ? where id = ?";
		Object[] params = new Object[]{notice.getTitle(),notice.getContent(),notice.getId()};
		try {
			queryRunner.update(sql, params);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}
	@Override
	public void deleteNotice(String id) {
		String sql ="delete from hr_notice where id = ? ";
		try {
			queryRunner.update(sql, id);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}